//
//  DYListViewController.swift
//  SheYangBigData
//
//  Created by 叁拾叁 on 2021/2/3.
//  Copyright © 2021 叁拾叁. All rights reserved.
//


import UIKit
import MJRefresh
import RxSwift
import RxDataSources
import Then
import SDCycleScrollView


class DYListViewController: SYBaseTableViewController {
    
    var tagView: DYDaoLanChoiceView!
    fileprivate var choiceDistanceView: VGBaseChoiceView<VGBaseChoiceOrgModel, VGChoiceNormalCell>!
    fileprivate var choiceTypeView: VGBaseChoiceView<VGBaseChoiceOrgModel, VGChoiceNormalCell>!
    fileprivate var choicePriceView: VGBaseChoiceView<VGBaseChoiceOrgModel, VGChoiceNormalCell>!
    fileprivate var vm: VGTableViewPageViewModel<DYListModel>!
    
    var params: [String: String] = [:]
    
    var listTypes:[VGBaseChoiceModel<VGBaseChoiceOrgModel>] = []
    
    var choiceModels: [DYJQTypeChoiceModel]!
    
    var paixunTitles:[String] = ["升序", "降序"]
    
    
    init(params:[String: String] = [:]) {
        super.init(nibName: nil, bundle: nil)
        self.params = params
        print("params1", params)
        params.forEach { (dict) in
            if dict.value.isEmpty {
                self.params.removeValue(forKey: dict.key)
            }
        }
        print("params2", params)
        self.params.removeAll()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = false
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.automaticallyAdjustsScrollViewInsets = false
        self.title = "景区景点"
        setTagView()
        setTableView()
        setNoDataView()
        setupViewModel()
        
    }
    
    fileprivate func setupViewModel() {
        vm = VGTableViewPageViewModel<DYListModel>()
        vm.tableView = tableView
        vm.emptyViewParams = ("", "", 40.0, 30.0)
        tableView.vg_pageProtocol = vm
        getData()
        getList()
        vm.getDataClosure = {[weak self] page in
            if let `self` = self {
                self.vm.getList(type: .dy_jingquSearch(page: self.vm.vg_pageNo, size:self.vm.size,  dic: self.params), dispose: self.dispose)
            }
        }
        vm.loadDataClosure = {[weak self] success in
            if let `self` = self {
                if success {
                    self.loadDataSuccessed()
                }
            }
        }
    }
    
    func getList() {
        
        vm.getList(type: .dy_jingquSearch(page: self.vm.vg_pageNo, size:self.vm.size,  dic: self.params), dispose: dispose)
        
    }
    
    func loadDataSuccessed() {
        DispatchQueue.main.async {
            
            self.setDataSource()
        }
    }
    
    
    func getData() {
        requestVM.baseRequest(disposeBag: dispose, type: .dy_jingquChoiceInfo(id: "2"), modelClass: SGBaseNoPageListModel<DYJQTypeChoiceModel>.self) {[weak self] (res) in
            if let `self` = self {
                
                self.choiceModels = res.data ?? []
                self.setupDistanceChoiceView()
                self.setupTypeChoiceView()
                self.setupPriceChoiceView()
            }
            
        } Error: {
            
        }
    }
    
    fileprivate func setupDistanceChoiceView() {
        
        self.choiceDistanceView = VGBaseChoiceView(frame: CGRect(x: 0, y: NAV_HEIGHT + 44.autoWidth(), width: SCREEN_WIDTH, height: SCREEN_HEIGHT - NAV_HEIGHT - 44.autoWidth()))
        view.addSubview(choiceDistanceView)
        self.choiceDistanceView.showSelf(false)
        choiceDistanceView.selectRowClosure = { [weak self] index in
            if let `self` = self {
                self.tagView.items[0].isSelected = false
                // ASC/正序、DESC/倒序
                var str = "ASC"
                if index == 1 {
                    str = "DESC"
                }
                self.params["distanceSort"] = str
                self.getList()
            }
        }
        choiceDistanceView.cancelClosure = {[weak self] in
            if let `self` = self {
                self.tagView.items[0].isSelected = false
            }
        }
        
        var lists:[VGBaseChoiceModel<VGBaseChoiceOrgModel>] = []
        self.paixunTitles.forEach({ (title) in
            let m: VGBaseChoiceModel<VGBaseChoiceOrgModel> = VGBaseChoiceModel<VGBaseChoiceOrgModel>()
            m.cellType = .normal
            m.cellModel = VGBaseChoiceOrgModel()
            m.cellModel!.title = title
//                    if self.tfText == m.cellModel!.title {
//                        m.isSelected = true
//                    }
            lists.append(m)
        })
        
                self.choiceDistanceView.setDataSource(lists, .noCancel)
    }
    
    fileprivate func setupTypeChoiceView() {
        
        self.choiceTypeView = VGBaseChoiceView(frame: CGRect(x: 0, y: NAV_HEIGHT + 44.autoWidth(), width: SCREEN_WIDTH, height: SCREEN_HEIGHT - NAV_HEIGHT - 44.autoWidth()))
        view.addSubview(choiceTypeView)
        self.choiceTypeView.showSelf(false)
        choiceTypeView.selectRowClosure = { [weak self] index in
            if let `self` = self {
                self.tagView.items[1].isSelected = false
                self.params["label"] = self.choiceModels[index].id
                self.getList()
            }
        }
        choiceTypeView.cancelClosure = {[weak self] in
            if let `self` = self {
                self.tagView.items[1].isSelected = false
            }
        }
        
        
        self.choiceModels.forEach({ (model) in
            let m: VGBaseChoiceModel<VGBaseChoiceOrgModel> = VGBaseChoiceModel<VGBaseChoiceOrgModel>()
            m.cellType = .normal
            m.cellModel = VGBaseChoiceOrgModel()
            m.cellModel!.title = model.dictionaryName
//                    if self.tfText == m.cellModel!.title {
//                        m.isSelected = true
//                    }
            listTypes.append(m)
        })
        
                self.choiceTypeView.setDataSource(listTypes, .noCancel)
    }
    
    fileprivate func setupPriceChoiceView() {
        
        self.choicePriceView = VGBaseChoiceView(frame: CGRect(x: 0, y: NAV_HEIGHT + 44.autoWidth(), width: SCREEN_WIDTH, height: SCREEN_HEIGHT - NAV_HEIGHT - 44.autoWidth()))
        view.addSubview(choicePriceView)
        self.choicePriceView.showSelf(false)
        choicePriceView.selectRowClosure = { [weak self] index in
            if let `self` = self {
                self.tagView.items[2].isSelected = false
                // ASC/正序、DESC/倒序
                var str = "ASC"
                if index == 1 {
                    str = "DESC"
                }
                self.params["ratesSort"] = str
                self.getList()
            }
        }
        choicePriceView.cancelClosure = {[weak self] in
            if let `self` = self {
                self.tagView.items[2].isSelected = false
            }
        }
        
        var lists:[VGBaseChoiceModel<VGBaseChoiceOrgModel>] = []
        self.paixunTitles.forEach({ (title) in
            let m: VGBaseChoiceModel<VGBaseChoiceOrgModel> = VGBaseChoiceModel<VGBaseChoiceOrgModel>()
            m.cellType = .normal
            m.cellModel = VGBaseChoiceOrgModel()
            m.cellModel!.title = title
//                    if self.tfText == m.cellModel!.title {
//                        m.isSelected = true
//                    }
            lists.append(m)
        })
        
                self.choicePriceView.setDataSource(lists, .noCancel)
    }
    
    func setTagView() {
        tagView = DYDaoLanChoiceView(frame: CGRect.init(x: 0, y: NAV_HEIGHT, width: SCREEN_WIDTH, height: 44.0.autoWidth()), titles: ["距离", "分类", "价格"])
        tagView.clickChoiceClosure = {[weak self] index in
            if let `self` = self {
                
                switch index {
                case 0:
                    self.choiceDistanceView.showSelf(self.choiceDistanceView.isHidden)
                    self.choiceTypeView.showSelf(false)
                    self.choicePriceView.showSelf(false)
                    self.tagView.items[1].isSelected = false
                    self.tagView.items[2].isSelected = false
                case 1:
                    self.choiceTypeView.showSelf(self.choiceTypeView.isHidden)
                    self.choiceDistanceView.showSelf(false)
                    self.choicePriceView.showSelf(false)
                    self.tagView.items[0].isSelected = false
                    self.tagView.items[2].isSelected = false
                case 2:
                    self.choicePriceView.showSelf(self.choicePriceView.isHidden)
                    self.choiceDistanceView.showSelf(false)
                    self.choiceTypeView.showSelf(false)
                    self.tagView.items[0].isSelected = false
                    self.tagView.items[1].isSelected = false
                    
                default:
                    break
                }
            }
        }
        view.addSubview(tagView)
    }
    
    func setTableView() {
        
        //创建表格视图
        self.tableView = UITableView(frame: CGRect(x: 0, y: NAV_HEIGHT+44.autoWidth(), width: SCREEN_WIDTH, height: SCREEN_HEIGHT-NAV_HEIGHT-BOTTOM_SAFE_HEIGHT-44.autoWidth()), style:.plain)
        self.tableView.separatorStyle = .none
        self.tableView!.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        self.view.addSubview(self.tableView!)
        
        tableView.rx.itemSelected
            .subscribe(onNext:{ [weak self] indexPath in
                if let `self` = self {
                    let m: DYListModel = (self.vm.dataSource[indexPath.row])
                    let vc = DYJingquDetailViewController(m.id ?? "0")
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            })
            .disposed(by:dispose)
    }
    
    func setNoDataView() {
        noDataView = SYNoDataView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-NAV_HEIGHT))
        noDataView.isHidden = true
        tableView.addSubview(noDataView)
    }
    
    func setDataSource() {
        //初始化数据
        let sections = Observable.just([
            DYListSection(header: "", items: self.vm.dataSource)
        ])
        
        //创建数据源
        let dataSource = RxTableViewSectionedAnimatedDataSource<DYListSection>(
            //设置单元格
            configureCell: { ds, tv, ip, item in
                
                
                let cell: DYDaoLanCell = tv.dequeueReusableCell(withIdentifier: "Cell")
                    as? DYDaoLanCell ?? DYDaoLanCell(style: .default, reuseIdentifier: "Cell")
                cell.configureListView(item)
                cell.selectionStyle = .none
                return cell
                
                
            },
            //设置分区头标题
            titleForHeaderInSection: { ds, index in
                return ds.sectionModels[index].header
            })
        tableView.dataSource = nil
        //绑定单元格数据
        sections
            .bind(to: tableView.rx.items(dataSource: dataSource))
            .disposed(by: dispose)
        
    }
    
    @objc func rightAction() {
        
    }
}


extension DYListViewController: SDCycleScrollViewDelegate {
    
    func cycleScrollView(_ cycleScrollView: SDCycleScrollView!, didSelectItemAt index: Int) {
        print("选择了轮播图\(index)")
    }
}



//自定义Section
struct DYListSection {
    var header: String
    var items: [Item]
}

extension DYListSection : AnimatableSectionModelType {
    typealias Item = DYListModel
    
    var identity: String {
        return header
    }
    
    init(original: DYListSection, items: [Item]) {
        self = original
        self.items = items
    }
}

extension DYListModel: IdentifiableType {
    var identity: String {
        return id!
    }
    
    typealias Identity = String
}
